//
//  CountDownButton.swift
//  Feicui
//
//  Created by people on 2018/4/27.
//  Copyright © 2018年 zhan. All rights reserved.
//
/*
 倒计时按钮
 */
import UIKit
import RxCocoa
import RxSwift
open class CountDownButton: UIButton {
    private var countdownTimer: Timer?
    private var temp : (()->())?
    private let disposeBag = DisposeBag()
    //变量remainingSeconds代表当前倒计时剩余的秒数：
    public var remainingSeconds: Int = 0 {
        willSet {
            self.setTitleColor(UIColor.RGB(r: 14, g: 185, b: 141), for: .normal)
            self.setTitle("(\(newValue)s)", for: .normal)
            if newValue <= 0 {
                self.setTitle("获取验证码", for: .normal)
                self.layer.borderColor = UIColor.blue.cgColor
                self.setTitleColor(UIColor.RGB(r: 14, g: 185, b: 141), for: .normal)
                isCounting = false
            }
        }
    }
    
    //变量开启或关闭定时器
    public var isCounting = false {
        willSet {
            if newValue {
                weak var weakSelf=self
                countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
                    weakSelf?.remainingSeconds -= 1
                })
                remainingSeconds = 60
                self.isUserInteractionEnabled = false;
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                self.isUserInteractionEnabled = true;
            }
            self.isEnabled = !newValue
        }
    }
    public func invalidate() {
        countdownTimer?.invalidate()
        countdownTimer = nil
    }
    

    //初始话
    override init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.rx.notification(NSNotification.Name("KillTimer"), object: nil).subscribe(onNext: {[weak self] (_) in
            print("收到销毁倒计时")
            self?.isCounting = false
        }).disposed(by: disposeBag)
    }
    //xib初始话
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

extension CountDownButton{
    //扩展 当重制 时间的时候 把 验证码重置
    public func setResetTime(withBlock block:(()->())?) -> Void {
        temp=block
    }
}
//扩展更新时间
extension CountDownButton{
    @objc public func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值

    }
    //开始启动
    @objc public func beginCountDown() {
        // 启动倒计时
        if !isCounting {
            isCounting = true
        }
    }
    public func beginCountDownNormal()  {
        if !isCounting {
            isCounting = true
        }
    }
}


